package com.zggk.framework.service.file;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.bean.Message;
import com.platform.framework.entity.file.BaseFileEntity;
import com.platform.framework.entity.file.CataLogue;
import com.platform.framework.service.BaseServiceImpl;
import com.zggk.framework.dao.file.BaseFileEntityRepository;
import com.zggk.framework.utils.FileUtils;

import io.minio.MinioClient;

@Service
public class BaseFileEntityService extends BaseServiceImpl{
	@Autowired
	BaseFileEntityRepository baseFileEntityRepository;
	
	/**
	 * 根据文件的md5信息查询是否有重复文件
	 * @param userCode
	 * @return
	 */
	public BaseFileEntity isExistFile(String md5) throws Exception{
		return baseFileEntityRepository.findByFileMd5(md5);
		
	}
	/**
	 * 
	 * @Description 根据用户名和md5判断是否为同一个用户上传相同的文件
	 * @author 尹强[yinqiang] Email:2259441906@qq.com Tel:18181725967
	 * @param
	 * @return
	 * @createDate 2018年11月3日上午10:01:48
	 * @update:2018年11月3日上午10:01:48
	 */
	public BaseFileEntity isExistFile(String md5,String userCode) throws Exception{
		 String sql = "SELECT * FROM basic.base_file_entity WHERE file_md5 = ? AND create_user_code = ? ";
		 List<BaseFileEntity> baseFileEntityList = this.getDao().findBySql(sql, new Object[] {md5,userCode}, BaseFileEntity.class);
		 if(baseFileEntityList.size() > 0) {
			 return  baseFileEntityList.get(0);
		 }
		 return null;
		 	
	}
	
	public Set<CataLogue> findFilePath() {
		//一级目录
		String[] fileDirectory = baseFileEntityRepository.findFileDirectory();
		Set<CataLogue> set=new HashSet<>();
		CataLogue cataLogue=null;
		for (String string : fileDirectory) {
			cataLogue=new CataLogue();
			cataLogue.setId(string);
			cataLogue.setName(string);
			cataLogue.setPid(null);
			set.add(cataLogue);
		}
		
		String[] filePath = baseFileEntityRepository.findFilePath();
		for (int i = 0; i < filePath.length; i++) {
			String firstIndex=filePath[i].substring(0,filePath[i].indexOf(","));
			String[] split = filePath[i].substring(filePath[i].indexOf(",")+1).split("/");
			for (int j = 0; j < split.length; j++) {
				cataLogue=new CataLogue();
				cataLogue.setPid(firstIndex);
				cataLogue.setName(split[j]);
				firstIndex=firstIndex+split[j]+"/";
				cataLogue.setId(firstIndex);
				set.add(cataLogue);
			}
		}
		
		
		List<BaseFileEntity> resultFile = baseFileEntityRepository.getBaseFileEntity();
		for (BaseFileEntity baseFileEntity : resultFile) {
			String pid=baseFileEntity.getFileDirectory()+baseFileEntity.getFilePath();
			System.out.println(pid);
			boolean flag=false;
			for (CataLogue cataLogue1 : set) {
				if(cataLogue1.getId().equals(pid)) {
					flag=true;
				}
			}
			if(flag) {
				cataLogue=new CataLogue();
				cataLogue.setId(baseFileEntity.getId());
				cataLogue.setPid(pid);
				cataLogue.setName(baseFileEntity.getFileName());
				set.add(cataLogue);
			}
		}
		
		return set;
	}
	
	
	public BaseFileEntity findByFileMd5(String md5) {
		return baseFileEntityRepository.findByFileMd5(md5);
	}

	
	/**
	 * 添加文件信息
	  * @Description .
	  * @param baseFile
	  * @return
	 */
	@Transactional
	public String saveFileInfo(BaseFileEntity baseFile){
		try{
			baseFileEntityRepository.save(baseFile);
			this.getLogDao().save(this.getOperationLog(OPERATE_TYPE_ADD, "多媒体文件实体表", "添加文件信息【"+JSONObject.toJSONString(baseFile)+"】"));
		}catch (Exception e) {
			return new Message(Message.ERROR, "添加文件信息失败").toJson();
		}
		return new Message(Message.OK, baseFile.getId()).toJson();
	}

	/**
	 * 
	  * @Description 根据点击的节点显示文件
	  * @author 杜天[dutian] Email:13594731440@163.com Tel:17600471932
	  * @param fileId
	  * @param pageable
	  * @return
	  * @throws Exception
	 */
	public Page<BaseFileEntity> findByFileIdAndPage(String fileId, Pageable pageable) throws Exception {
		String[] fileDirectorys = baseFileEntityRepository.findFileDirectory();
		String filePath="";
		String fileDirectory="";
		for (String string : fileDirectorys) {
			if(fileId.equals(string)) {
				return null;
			}
			if(fileId.startsWith(string)) {
				fileDirectory=string;
				filePath=fileId.substring(fileId.indexOf(string)+string.length());
			}
		}
		//是叶子节点直接查id,不是查filePath
		if(filePath.equals("")&&fileDirectory.equals("")) {
			return this.getDao().findEntityPagingBySql("select * from  basic.base_file_entity where id=?", new Object[] {fileId}, pageable, BaseFileEntity.class);
		}else {
			return 	this.getDao().findEntityPagingBySql("select * from  basic.base_file_entity where file_directory =? and file_path like ?", new Object[]{fileDirectory,filePath + '%'}, pageable, BaseFileEntity.class);
		}
	}
	
	
	/**
	 * 
	 * 
	 * @Description 删除选中的文件,minio服务器上的文件也删除
	 * @author 杜天[dutian] Email:13594731440@163.com Tel:17600471932
	 * @param ids
	 * @return
	 */
	@Transactional
	public String deleteFiles(String ids) {
		String[] idArr = ids.split(",");
		int lens = idArr.length;
		MinioClient minioClient = FileUtils.getInstance();
		try {
			for (int i = 0; i < lens; i++) {
				BaseFileEntity baseFileEntity = baseFileEntityRepository.findOne(idArr[i]);
				baseFileEntityRepository.delete(baseFileEntity);
				// 同步minio服务器,如果是图片同时删除缩略图
				minioClient.removeObject(baseFileEntity.getFileDirectory(), baseFileEntity.getFilePath()+baseFileEntity.getFileNewName());
				if(FileUtils.isImage(baseFileEntity.getFileType())) {
					minioClient.removeObject(baseFileEntity.getFileDirectory(), baseFileEntity.getFilePath()+"thumbs/"+baseFileEntity.getFileNewName());
				}
			}
		} catch (Exception e) {
			return new Message(Message.ERROR, "删除数据字典失败").toJson();
		}
		return new Message(Message.OK, lens + "").toJson();
	}

	@Transactional
	public void downLoadById(String id ,HttpServletResponse response) {
		InputStream in = null;
        OutputStream out = null;
        BaseFileEntity baseFileEntity = baseFileEntityRepository.findOne(id);
        MinioClient minioClient = FileUtils.getInstance();
        try
        {
          in = minioClient.getObject(baseFileEntity.getFileDirectory(), baseFileEntity.getFilePath()+baseFileEntity.getFileNewName());
          int len = 0;
          byte[] buffer = new byte[1024];
          out = response.getOutputStream();
          response.reset();
          response.addHeader("Content-Disposition",    
        	      " attachment;filename=" + new String(baseFileEntity.getFileName().getBytes(),"iso-8859-1"));
          response.setContentType("application/octet-stream");
          while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
          }
        }
        catch (Exception e)
        {
        	e.printStackTrace();
        }
        finally
        {
          if (in != null) {
            try
            {
              in.close();
            }
            catch (Exception e)
            {
              throw new RuntimeException(e);
            }
          }
          if (out != null) {
            try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
          }
        }
	}

	public void downLoadpdfById(String id, HttpServletResponse response) {
	       	InputStream in = null;
	        OutputStream out = null;
	        BaseFileEntity baseFileEntity = baseFileEntityRepository.findOne(id);
	        MinioClient minioClient = FileUtils.getInstance();
	        try
	        {
	          in = minioClient.getObject(baseFileEntity.getFileDirectory(), baseFileEntity.getFilePath()+baseFileEntity.getFileNewName());
	          int len = 0;
	          byte[] buffer = new byte[1024];
	          out = response.getOutputStream();
	          response.reset();
	          response.addHeader("Content-Disposition",    
	        	      " attachment;filename=" + new String(baseFileEntity.getFileName().getBytes(),"iso-8859-1"));
	          response.setContentType("application/pdf;charset=UTF-8");
	          while ((len = in.read(buffer)) > 0) {
	            out.write(buffer, 0, len);
	          }
	        }
	        catch (Exception e)
	        {
	        	e.printStackTrace();
	        }
	        finally
	        {
	          if (in != null) {
	            try
	            {
	              in.close();
	            }
	            catch (Exception e)
	            {
	              throw new RuntimeException(e);
	            }
	          }
	          if (out != null) {
	            try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	          }
	        }
	}
	
	
	
}
